import express from "express";

import { db } from "../database.js";
import { auth } from "../auth.js";
import { validate, validators } from "../validate.js";

// 定义子路由
const router = express.Router();

// 使用中间件验证用户登录状态
router.use(auth);
// 定义中间件验证代办信息是否存在
async function existsTodo(req, res, next) {
  const { tid } = req.params;
  const userId = req.session.userId;
  // 查询待办是否存在
  const todo =
    await db.findOne`select * from todo where id = ${tid} and user_id = ${userId}`;
  if (!todo) {
    return res.status(404).json({ success: false, message: "待办不存在" });
  }
  next();
}

// 定义路由
router
  .get(
    "/todo",
    validate(validators.limit, validators.offset),
    async (req, res) => {
      const { limit = 10, offset = 0 } = req.query;
      const userId = req.session.userId;
      // 查询待办列表
      const todos =
        await db.findMany`select * from todo where user_id = ${userId} limit ${limit} offset ${offset}`;
      // 查询待办总数
      const { count } =
        await db.findOne`select count(*) as count from todo where user_id = ${userId}`;
      res.json({
        success: true,
        query: { count, limit, offset, results: todos },
      });
    }
  )
  // 添加待办
  .post(
    "/todo",
    validate(validators.title, validators.description, validators.priority),
    async (req, res) => {
      const { title, description, priority } = req.body;
      const userId = req.session.userId;
      // 保存待办信息
      const todo =
        await db.insert`insert into todo (user_id, title, description, priority)
        values (${userId}, ${title}, ${description}, ${priority})`;
      res.json({ success: true, message: "添加待办成功", object: todo });
    }
  )
  .put(
    "/todo/:tid",
    validate(
      validators.todoId,
      validators.title,
      validators.description,
      validators.priority
    ),
    existsTodo,
    async (req, res) => {
      const { tid } = req.params;
      const { title, description, priority } = req.body;
      const userId = req.session.userId;
      // 更新待办信息
      await db.update`update todo set title = ${title}, description = ${description}, priority = ${priority} where id = ${tid} and user_id = ${userId}`;
      const todo = await db.findOne`select * from todo where id = ${tid}`;
      res.json({ success: true, message: "更新待办成功", object: todo });
    }
  )
  .put(
    "/todo/:tid/done",
    validate(validators.todoId),
    existsTodo,
    async (req, res) => {
      const { tid } = req.params;
      const userId = req.session.userId;
      const affectedRows =
        await db.update`update todo set finished_at = current_timestamp where id = ${tid} and user_id = ${userId}`;
      if (affectedRows == 0) {
        return res.status(404).json({ success: false, message: "待办不存在" });
      }
      const todo = await db.findOne`select * from todo where id = ${tid}`;
      res.json({ success: true, message: "更新待办状态成功", object: todo });
    }
  )
  .delete(
    "/todo/:tid",
    validate(validators.todoId),
    existsTodo,
    async (req, res) => {
      const { tid } = req.params;
      const userId = req.session.userId;

      await db.delete`delete from todo where id = ${tid} and user_id = ${userId}`;
      res.json({ success: true, message: "删除待办成功" });
    }
  );

export default router;
